package com.lee.starter.db.config;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.lee.starter.response.PageData;
import com.lee.starter.response.Result;
import com.lee.starter.response.enhancer.IResultHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @author lee
 * @since 2019-11-22
 */
@Configuration
@ComponentScan("com.lee.starter.db")
public class MybatisPlusConfig {

    /**
     * 分页插件，自动识别数据库类型 多租户，请参考官网【插件扩展】
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        // paginationInterceptor.setLimit(500);

        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    /**
     * controller 回复增强（主要针对IPage数据）
     */
    @Bean
    public IResultHandler customResultHandler() {
        return (body -> {
            if (body instanceof IPage) {
                IPage<?> page = (IPage<?>) body;
                PageData pageData = new PageData(page.getCurrent(), page.getTotal(), page.getSize(), page.getRecords());
                return Result.success(pageData);
            } else {
                return Result.success(body);
            }
        });
    }
}
